<template>
    <div class="header">
        <el-row :gutter="0">
            <el-col :span="6" :offset="3">
                <!-- 搜索 -->
                <el-autocomplete v-model="state" :fetch-suggestions="querySearchAsync" :placeholder="placeholderValue"
                    @select="handleSelect" @keydown.enter="handleEnter">
                    <template #prefix>
                        <el-icon>
                            <Search />
                        </el-icon>
                    </template>
                    <template #default="{ item }">
                        <div class="value">{{
                            item.searchWord
                        }}<el-image :src="item.iconUrl" v-if="item.iconUrl" class="hot-image"></el-image>
                        </div>
                    </template>
                </el-autocomplete>
            </el-col>
            <el-col :span="4" :offset="10">
                <div v-if="useCookie().cookie != null" class="avatar">
                    <el-dropdown>
                        <!-- <span>1</span> -->
                        <el-avatar size="default" :src="useUser().user.avatarUrl"
                            v-if="useUser().user.avatarUrl"></el-avatar>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item
                                    @click="MyHome">我&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;的</el-dropdown-item>
                                <el-dropdown-item @click="register">退出登录</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
                <div v-else class="no-login">
                    <el-button link text @click="login">去登录</el-button>
                </div>
            </el-col>
        </el-row>
    </div>

    <el-dialog v-model="centerDialogVisible" :title="title" width="500px" center @open="openDialog" @close="closeDialog">
        <el-row v-if="showQr">
            <el-col :span="10">
                <img src="http://up.quarkzhong.top/imgs/2024/01/c7c358ddaa465173.png" alt="" style="width: 80%;">
            </el-col>
            <el-col :span="14">
                <img :src="qrUrl" alt="二维码" style="width: 100%;">
                <div style="text-align: center;">
                    <span>使用 <el-link type="primary">网易云音乐APP</el-link> 扫码登录</span>
                </div>
            </el-col>
            <el-col :span="24">
                <div style="text-align: center;margin-top: 20px;">
                    <el-button round @click="anonimous">选择其他登录模式 / 游客登录</el-button>
                </div>
            </el-col>
            <el-col :span="24">
                <div style="text-align: right;"><el-link @click="showQr = false; title = '密码登录'">切换密码登录</el-link></div>
            </el-col>
        </el-row>
        <el-row v-else>
            <el-col :span="24">
                <el-form ref="formref" :model="form" :rules="rules" label-width="80px">
                    <el-form-item label="手机号" prop="phone">
                        <el-input placeholder="请填写手机号" :maxLength="11" v-model="form.phone" clearable>
                            <template #prepend>
                                <span>+86</span>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input placeholder="请填写密码" :maxLength="20" v-model="form.password" type="password"
                            show-password></el-input>
                    </el-form-item>
                </el-form>
            </el-col>
            <el-col :span="24">
                <div style="text-align: center;margin-top: 20px;">
                    <el-button @click="loginPassword">登录账号</el-button>
                </div>
            </el-col>

            <el-col :span="24">
                <div style="text-align: right;"><el-link @click="showQr = true; title = '扫码登录'">切换扫码登录</el-link></div>
            </el-col>
        </el-row>
    </el-dialog>
</template>

<script setup>
import { useUser } from '@/stores/user'
import { useCookie } from '@/stores/cookie'
import { onMounted, ref, watch } from 'vue'
import { loginCellphone, getSearchHotDetail, getSearchDefault, getLoginQrKey, getLoginQrCreate, getLoginQrCheck, registerAnonimous, getUserAccount, getLoginRefresh, getLogout, getUserDetail } from '@/api/header'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
const user = useUser()
const showQr = ref(true)
const centerDialogVisible = ref(false)
const title = ref('扫码登录')
const router = useRouter()
const state = ref('')
const hotList = ref([])
const qrUrl = ref('https://music.163.com/login?codekey=a5dcf940-f5c0-48b7-9620-e3fac76e4cb8')
const dsq = ref(null)
const form = ref({
    phone: '',
    password: ''
})
const rules = ref({
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { min: 11, max: 11, message: '手机号长度应为11位', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 25, message: '密码长度为6-25位', trigger: 'blur' },
    ]
})
onMounted(async () => {
    try {
        const res = await getSearchHotDetail()
        hotList.value = res.data
    } catch (e) {
        console.log(e)
    }
    try {
        const res2 = await getSearchDefault()
        placeholderValue.value = res2.data.showKeyword
    } catch (e) {
        console.log(e)
    }
})
const querySearchAsync = async (queryString, cb) => {
    if (queryString != '') {
        cb([])
        return
    }
    cb(hotList.value)
}
const placeholderValue = ref('请输入搜索内容')
const handleSelect = (row) => {
    state.value = row.searchWord
}
const handleEnter = () => {
    if (state.value == '') {
        state.value = placeholderValue.value
    }
    router.push({
        path: '/search',
        query: {
            keywords: state.value
        }
    })
}
const MyHome = () => {
    router.push({
        path: '/user/home'
    })
}
const login = () => {
    title.value = '登录'
    user.loginfrom = true
}

const register = async () => {
    const res = await getLogout()
    if (res.code == 200) {
        ElMessage({
            message: '退出成功',
            type: 'success'
        })

        useCookie().removeCookie()
        // useUser().removeUser()
    }
}
const getUserInfo = async () => {
    const res = await getUserAccount()
    const res2 = await getUserDetail(res.profile.userId || useUser().user.userId)
    useUser().user = res2.profile
}
const openDialog = async () => {
    // await getLoginRefresh()
    const res = await getLoginQrKey()
    const key = res.data.unikey
    const res2 = await getLoginQrCreate(key)
    qrUrl.value = res2.data.qrimg
    dsq.value = setInterval(async () => {
        const res3 = await getLoginQrCheck(key)
        if (res3.code == 803) {
            useCookie().cookie = encodeURIComponent(res3.cookie)
            getUserInfo()
            title.value = '登录成功'
            user.loginfrom = false
            clearInterval(dsq.value)
        }
        if (res3.code == 800) {
            clearInterval(dsq.value)
            ElMessage({
                message: '二维码已失效',
                type: 'error'
            })
            openDialog()
        }

    }, 1000)
}
const anonimous = async () => {
    const res = await registerAnonimous()
    useCookie().cookie = encodeURIComponent(res.cookie)
    user.loginfrom = false
}
const closeDialog = () => {
    clearInterval(dsq.value)
    user.loginfrom = false
}
const loginPassword = async () => {

    const res = await loginCellphone({
        phone: form.value.phone,
        password: form.value.password
    })
    useCookie().cookie = encodeURIComponent(res.cookie)
    useUser().user = res.profile
    getUserInfo()
    title.value = '登录成功'
    user.loginfrom = false
}

watch(() => user.loginfrom, (newVal) => {
    centerDialogVisible.value = newVal
}, { deep: true, immediate: true })
</script>

<style lang="less" scoped>
.header {
    height: 60px;
    background-color: #fff;
    border-bottom: 1px solid #ebeef5;

    .el-row {
        height: 100%;

        .el-col {
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;

            .el-image {
                width: 40px;
                height: 40px;
                border-radius: 50%;
            }
        }
    }
}

.no-login {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;

    .el-button {
        margin-left: 10px;
    }

}

.hot-image {
    height: 12px;
    margin-left: 5px;
}
</style>